package com.kurumi.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.kurumi.config.MyConfig;
import com.kurumi.pojo.MedicalRecord;
import com.kurumi.pojo.RespondResult;
import com.kurumi.query.MedicalRecordQuery;
import com.kurumi.service.InterfaceMedicalRecord1Service;
import com.kurumi.service.MedicalRecordService;
import com.kurumi.util.DateUtil;
import com.kurumi.util.HttpClientUtil;
import com.kurumi.util.ListPagination;

@Controller
@RequestMapping("/interface_medical_record1")
public class InterfaceMedicalRecord1Controller {
	
	@Autowired
	private MyConfig myConfig;

	@Autowired
	private MedicalRecordService medicalRecordService;
	
	@Autowired
	private InterfaceMedicalRecord1Service interfaceMedicalRecord1Service;
	
	@GetMapping("/interface_query_form")
	public String pigeonholedIndex(){
		
		
		return "interface/interface_query";
	}
	
	@GetMapping("/interface_query_qf_dr_page")
	public String interfaceQueryQfDR(){
		
		
		return "interface/interface_query_qf_dr";
	}
	
	@GetMapping("/interface_query_qf_dr_page_pt")
	public String interfaceQueryQfDRPt(){
		
		
		return "interface/interface_query_qf_dr_pt";
	}
	
	@GetMapping("/ajax_query_interface_medical_record")
	@ResponseBody
	public RespondResult ajaxQueryInterfaceMedicalRecord(MedicalRecordQuery query,HttpServletResponse response){
		
		RespondResult respondResult = null;
		
		try{
			Map<String, String> param = new HashMap<String, String>();
			param.put("onlyId", query.getOnlyId());
			param.put("mrId", query.getMrId());
			param.put("patientName", query.getPatientName());
			param.put("idNumber", query.getIdNumber());
			
			if(query.getOutHospitalStartDate() != null){
				param.put("outHospitalStartDate", DateUtil.dateFormat(query.getOutHospitalStartDate()));
			}else{
				param.put("outHospitalStartDate",null);
			}
			
			if(query.getOutHospitalEndDate() != null){
				param.put("outHospitalEndDate", DateUtil.dateFormat(query.getOutHospitalEndDate()));
			}else{
				param.put("outHospitalEndDate",null);
			}
			param.put("currentPage", ""+query.getCurrentPage());
			param.put("outHospitalDeptCode", query.getOutHospitalDeptCode());
			String userJson = HttpClientUtil.doGet(myConfig.getRemoteInterfaceUrl()+"interface_data3/remote_query_interface_medical_record", param);
			if(userJson != null){
				JSONObject userMap =JSONObject.parseObject(userJson);
				boolean success = userMap.getBoolean("success");
				if(success){
					
					List<Map<String, Object>> datas = (List<Map<String, Object>>)userMap.get("datas");
					for (Map<String, Object> data : datas) {
						String onlyId = (String)data.get("onlyId".toUpperCase());
						String mrId = (String)data.get("mrId".toUpperCase());
						Integer visitNumber = (Integer)data.get("visitNumber".toUpperCase());
						int count = medicalRecordService.checkMeditalRecordUniq(onlyId, mrId, visitNumber);
						if(count ==1){
							data.put("isExsit", 1);
						}else{
							data.put("isExsit", 0);
						}
						
					}
					query.setTotalCounts(datas.size());
					ListPagination list = new ListPagination<Map<String, Object>>(datas, query.getCurrentPage(), query.getPageSize());
					query.setQueryDatas(list.getList());
					return new RespondResult(true, RespondResult.successCode, "成功", query);
					
					
				}else{
					String stateMessage = userMap.getString("stateMessage");
					return new RespondResult(true, RespondResult.errorCode,"EMR接口接通，接口内部错误",stateMessage);
				}
			}else{
				return new RespondResult(true, RespondResult.errorCode, "访问EMR接口应用失败", "访问EMR接口应用失败");
			}
			
			
			
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			respondResult = new RespondResult(false, RespondResult.errorCode, "查询失败！不可预期错误！", e.getMessage());
		}
		
		return respondResult;
	}
	
	@GetMapping("/ajax_query_interface_medical_record_dr")
	@ResponseBody
	public RespondResult ajaxQueryInterfaceMedicalRecordDr(MedicalRecordQuery query,HttpServletResponse response){
		
		RespondResult respondResult = null;
		
		try{
			Map<String, String> param = new HashMap<String, String>();
			param.put("onlyId", query.getOnlyId());
			param.put("mrId", query.getMrId());
			param.put("patientName", query.getPatientName());
			param.put("idNumber", query.getIdNumber());
			
			if(query.getOutHospitalStartDate() != null){
				param.put("outHospitalStartDate", DateUtil.dateFormat(query.getOutHospitalStartDate()));
			}else{
				param.put("outHospitalStartDate",null);
			}
			
			if(query.getOutHospitalEndDate() != null){
				param.put("outHospitalEndDate", DateUtil.dateFormat(query.getOutHospitalEndDate()));
			}else{
				param.put("outHospitalEndDate",null);
			}
			param.put("currentPage", ""+query.getCurrentPage());
			param.put("outHospitalDeptCode", query.getOutHospitalDeptCode());
			String userJson = HttpClientUtil.doGet(myConfig.getRemoteInterfaceUrl()+"interface_data_qf_dr/remote_query_interface_medical_record", param);
			if(userJson != null){
				JSONObject userMap =JSONObject.parseObject(userJson);
				boolean success = userMap.getBoolean("success");
				if(success){
					
					List<Map<String, Object>> datas = (List<Map<String, Object>>)userMap.get("datas");
					for (Map<String, Object> data : datas) {
						String onlyId = (String)data.get("onlyId".toUpperCase());
						String mrId = (String)data.get("mrId".toUpperCase());
						Integer visitNumber = (Integer)data.get("visitNumber".toUpperCase());
						int count = medicalRecordService.checkMeditalRecordUniq(onlyId, mrId, visitNumber);
						if(count ==1){
							data.put("isExsit", 1);
						}else{
							data.put("isExsit", 0);
						}
						
					}
					query.setTotalCounts(datas.size());
					ListPagination list = new ListPagination<Map<String, Object>>(datas, query.getCurrentPage(), query.getPageSize());
					query.setQueryDatas(list.getList());
					return new RespondResult(true, RespondResult.successCode, "成功", query);
					
					
				}else{
					String stateMessage = userMap.getString("stateMessage");
					return new RespondResult(true, RespondResult.errorCode,"EMR接口接通，接口内部错误",stateMessage);
				}
			}else{
				return new RespondResult(true, RespondResult.errorCode, "访问EMR接口应用失败", "访问EMR接口应用失败");
			}
			
			
			
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			respondResult = new RespondResult(false, RespondResult.errorCode, "查询失败！不可预期错误！", e.getMessage());
		}
		
		return respondResult;
	}
	

	@GetMapping("/ajax_query_interface_medical_record_dr_pt")
	@ResponseBody
	public RespondResult ajaxQueryInterfaceMedicalRecordDrPt(MedicalRecordQuery query,HttpServletResponse response){
		
		RespondResult respondResult = null;
		
		try{
			Map<String, String> param = new HashMap<String, String>();
			param.put("onlyId", query.getOnlyId());
			param.put("mrId", query.getMrId());
			param.put("patientName", query.getPatientName());
			param.put("idNumber", query.getIdNumber());
			
			if(query.getOutHospitalStartDate() != null){
				param.put("outHospitalStartDate", DateUtil.dateFormat(query.getOutHospitalStartDate()));
			}else{
				param.put("outHospitalStartDate",null);
			}
			
			if(query.getOutHospitalEndDate() != null){
				param.put("outHospitalEndDate", DateUtil.dateFormat(query.getOutHospitalEndDate()));
			}else{
				param.put("outHospitalEndDate",null);
			}
			param.put("currentPage", ""+query.getCurrentPage());
			param.put("outHospitalDeptCode", query.getOutHospitalDeptCode());
			String userJson = HttpClientUtil.doGet(myConfig.getRemoteInterfaceUrl()+"interface_data_qf_dr/remote_query_interface_medical_record_pt", param);
			if(userJson != null){
				JSONObject userMap =JSONObject.parseObject(userJson);
				boolean success = userMap.getBoolean("success");
				if(success){
					
					List<Map<String, Object>> datas = (List<Map<String, Object>>)userMap.get("datas");
					for (Map<String, Object> data : datas) {
						String onlyId = (String)data.get("onlyId".toUpperCase());
						String mrId = (String)data.get("mrId".toUpperCase());
						Integer visitNumber =Integer.parseInt(data.get("visitNumber".toUpperCase()).toString());
						int count = medicalRecordService.checkMeditalRecordUniq(onlyId, mrId, visitNumber);
						if(count ==1){
							data.put("isExsit", 1);
						}else{
							data.put("isExsit", 0);
						}
						
					}
					query.setTotalCounts(datas.size());
					ListPagination list = new ListPagination<Map<String, Object>>(datas, query.getCurrentPage(), query.getPageSize());
					query.setQueryDatas(list.getList());
					return new RespondResult(true, RespondResult.successCode, "成功", query);
					
					
				}else{
					String stateMessage = userMap.getString("stateMessage");
					return new RespondResult(true, RespondResult.errorCode,"EMR接口接通，接口内部错误",stateMessage);
				}
			}else{
				return new RespondResult(true, RespondResult.errorCode, "访问EMR接口应用失败", "访问EMR接口应用失败");
			}
			
			
			
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			respondResult = new RespondResult(false, RespondResult.errorCode, "查询失败！不可预期错误！", e.getMessage());
		}
		
		return respondResult;
	}
	
	@PostMapping("/ajax_extract_medical_record")
	@ResponseBody
	public RespondResult ajaxExtractMedicalRecord(String mrId,String visitNumber){
		
		RespondResult respondResult = null;
		
		try{
			Map<String, String> param = new HashMap<String, String>();
			param.put("mrId", mrId);
			param.put("visitNumber", visitNumber);
			String userJson = HttpClientUtil.doGet(myConfig.getRemoteInterfaceUrl()+"interface_data3/remote_extract_interface_medical_record", param);
			if(userJson != null){
				JSONObject userMap =JSONObject.parseObject(userJson);
				boolean success = userMap.getBoolean("success");
				if(success){
					
					Map<String, Object> data = (Map<String, Object>)userMap.get("datas");
					Map<String, Object> jsonMap = (Map<String, Object>)data.get("jsonMap");
					Map<String, Object> medicalRecordMap = (Map<String, Object>)data.get("medicalRecord");
					MedicalRecord medicalRecord = MedicalRecord.buildMedicalRecord(medicalRecordMap);
					int count = interfaceMedicalRecord1Service.extractInterfaceMedicalRecordOfPage(medicalRecord, jsonMap);
					if(count == 1){
						return new RespondResult(true, RespondResult.successCode, "提取成功", medicalRecordMap);
					}else if(count == 2){
						return new RespondResult(true, RespondResult.repeatCode, "已提取过，请勿重复提取", medicalRecordMap);
					}
					else{
						return new RespondResult(true, RespondResult.errorCode, "提取失败", medicalRecordMap);
					}
					
				}else{
					String stateMessage = userMap.getString("stateMessage");
					if(stateMessage == null){
						stateMessage = "访问接口应用失败";
					}
					return new RespondResult(true, RespondResult.errorCode,stateMessage, "");
				}
			}else{
				return new RespondResult(true, RespondResult.errorCode, "访问接口应用失败", "");
			}
			
			
			
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			respondResult = new RespondResult(false, RespondResult.errorCode, e.getMessage(), "");
		}
		
		return respondResult;
	}
	
	@PostMapping("/ajax_extract_medical_record_qf_dr")
	@ResponseBody
	public RespondResult ajaxExtractMedicalRecordQfDr(String mrId,String visitNumber,String onlyId,HttpServletRequest request){
		
		RespondResult respondResult = null;
		
		try{
			HttpSession session = request.getSession();
			Map<String, Object> currentUser = (Map<String, Object>)session.getAttribute("currentUser");
			System.out.println(currentUser);
			String userCode =(String)currentUser.get("user_code");
			String userName =(String)currentUser.get("user_name");
			Map<String, String> param = new HashMap<String, String>();
			param.put("onlyId", onlyId);
			param.put("mrId", mrId);
			param.put("visitNumber", visitNumber);
			param.put("userCode", StringUtils.isEmpty(userCode)?null:userCode);
			param.put("userName", StringUtils.isEmpty(userName)?null:userName);
			String userJson = HttpClientUtil.doGet(myConfig.getRemoteInterfaceUrl()+"interface_data_qf_dr/remote_extract_interface_medical_record", param);
			if(userJson != null){
				JSONObject userMap =JSONObject.parseObject(userJson);
				boolean success = userMap.getBoolean("success");
				if(success){
					
					Map<String, Object> data = (Map<String, Object>)userMap.get("datas");
					Map<String, Object> jsonMap = (Map<String, Object>)data.get("jsonMap");
					Map<String, Object> medicalRecordMap = (Map<String, Object>)data.get("medicalRecord");
					MedicalRecord medicalRecord = MedicalRecord.buildMedicalRecord(medicalRecordMap);
					int count = interfaceMedicalRecord1Service.extractInterfaceMedicalRecordOfPage(medicalRecord, jsonMap);
					if(count == 1){
						return new RespondResult(true, RespondResult.successCode, "提取成功", medicalRecordMap);
					}else if(count == 2){
						return new RespondResult(true, RespondResult.repeatCode, "已提取过，请勿重复提取", medicalRecordMap);
					}
					else{
						return new RespondResult(true, RespondResult.errorCode, "提取失败", medicalRecordMap);
					}
					
				}else{
					String stateMessage = userMap.getString("stateMessage");
					if(stateMessage == null){
						stateMessage = "访问接口应用失败";
					}
					return new RespondResult(true, RespondResult.errorCode,stateMessage, "");
				}
			}else{
				return new RespondResult(true, RespondResult.errorCode, "访问接口应用失败", "");
			}
			
			
			
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			respondResult = new RespondResult(false, RespondResult.errorCode, e.getMessage(), "");
		}
		
		return respondResult;
	}
	
	
	@PostMapping("/ajax_extract_medical_record_qf_dr_pt")
	@ResponseBody
	public RespondResult ajaxExtractMedicalRecordQfDrPt(String mrId,String visitNumber,String onlyId,HttpServletRequest request){
		
		RespondResult respondResult = null;
		
		try{
			HttpSession session = request.getSession();
			Map<String, Object> currentUser = (Map<String, Object>)session.getAttribute("currentUser");
			System.out.println(currentUser);
			String userCode =(String)currentUser.get("user_code");
			String userName =(String)currentUser.get("user_name");
			Map<String, String> param = new HashMap<String, String>();
			param.put("onlyId", onlyId);
			param.put("mrId", mrId);
			param.put("visitNumber", visitNumber);
			param.put("userCode", StringUtils.isEmpty(userCode)?null:userCode);
			param.put("userName", StringUtils.isEmpty(userName)?null:userName);
			String userJson = HttpClientUtil.doGet(myConfig.getRemoteInterfaceUrl()+"interface_data_qf_dr/remote_extract_interface_medical_record_pt", param);
			if(userJson != null){
				JSONObject userMap =JSONObject.parseObject(userJson);
				boolean success = userMap.getBoolean("success");
				if(success){
					
					Map<String, Object> data = (Map<String, Object>)userMap.get("datas");
					Map<String, Object> jsonMap = (Map<String, Object>)data.get("jsonMap");
					Map<String, Object> medicalRecordMap = (Map<String, Object>)data.get("medicalRecord");
					MedicalRecord medicalRecord = MedicalRecord.buildMedicalRecord(medicalRecordMap);
					int count = interfaceMedicalRecord1Service.extractInterfaceMedicalRecordOfPage(medicalRecord, jsonMap);
					if(count == 1){
						return new RespondResult(true, RespondResult.successCode, "提取成功", medicalRecordMap);
					}else if(count == 2){
						return new RespondResult(true, RespondResult.repeatCode, "已提取过，请勿重复提取", medicalRecordMap);
					}
					else{
						return new RespondResult(true, RespondResult.errorCode, "提取失败", medicalRecordMap);
					}
					
				}else{
					String stateMessage = userMap.getString("stateMessage");
					if(stateMessage == null){
						stateMessage = "访问接口应用失败";
					}
					return new RespondResult(true, RespondResult.errorCode,stateMessage, "");
				}
			}else{
				return new RespondResult(true, RespondResult.errorCode, "访问接口应用失败", "");
			}
			
			
			
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			respondResult = new RespondResult(false, RespondResult.errorCode, e.getMessage(), "");
		}
		
		return respondResult;
	}
	
	@GetMapping("/interface_synchro_page")
	public String interfaceSynchroPage(Model model){
		return "interface/interface_synchro_page";
	}
	
	
	@PostMapping("/ajax_extract_medical_record_cost")
	@ResponseBody
	public RespondResult ajaxExtractMedicalRecordCost(String visitGuid,String mrId,String visitNumber,String onlyId){
		
		RespondResult respondResult = null;
		
		try{
			Map<String, String> param = new HashMap<String, String>();
			param.put("visitGuid", visitGuid);
			param.put("mrId", mrId);
			param.put("visitNumber", visitNumber);
			param.put("onlyId", onlyId);
			String userJson = HttpClientUtil.doGet(myConfig.getRemoteInterfaceUrl()+"interface_data_qf_dr/remote_extract_interface_cost", param);
			if(userJson != null){
				JSONObject userMap =JSONObject.parseObject(userJson);
				boolean success = userMap.getBoolean("success");
				if(success){
					
					Map<String, Object> jsonMap = (Map<String, Object>)userMap.get("datas");
					Map<String, Object> costMap = (Map<String, Object>)jsonMap.get("costInfo");
					int count = interfaceMedicalRecord1Service.extractInterfaceMedicalRecordOfCost(visitGuid, costMap);
					if(count == 1){
						return new RespondResult(true, RespondResult.successCode, "提取成功", jsonMap);
					}
					else{
						return new RespondResult(true, RespondResult.errorCode, "提取失败", jsonMap);
					}
				}else{
					String stateMessage = userMap.getString("stateMessage");
					if(stateMessage == null){
						stateMessage = "访问接口应用失败";
					}
					return new RespondResult(true, RespondResult.errorCode,stateMessage, "");
				}
			}else{
				return new RespondResult(true, RespondResult.errorCode, "访问接口应用失败", "");
			}
			
			
			
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			respondResult = new RespondResult(false, RespondResult.errorCode, e.getMessage(), "");
		}
		
		return respondResult;
	}
	
	
}
